Ext.ns('designer');

designer.controllerUrl = '';
/*
 * Message box fom ExtJS Examples
 */
designer.msgCt = false;
designer.createBox = function(t, s){
    return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
};

designer.msg = function(title ,  text){

	if(!designer.msgCt){
		designer.msgCt = Ext.core.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
    }
    var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
    var m = Ext.core.DomHelper.append(designer.msgCt, designer.createBox(title, s), true);
    m.hide();
    m.slideIn('t').ghost("t", { delay: 2000, remove: true});
};

Ext.define('designer.application',{
	extend:'Ext.Panel',
	
	rightPanel:null,
	centerPanel:null,	
	
	rightTop:null,
	rightBottom:null,
	componentsBar:null,
	topToolbar:null,
	
	activePropertyPanel:null,
	
	initComponent:function(){	
		this.initLayout();
		this.initToolbars();
		this.callParent(arguments);
		this.on('afterrender',function(){
			this.prepareInterface(false);
			this.checkIsLoaded();
		},this);	
	},
	
	initLayout:function(){
		this.layout = 'border';
		
		
		// Right
		this.rightTop = Ext.create('designer.objects.Panel',{
			region:'north',
			split:true,
			height:300,
			collapsible:true,
			controllerUrl:app.createUrl([designer.controllerUrl ,'objects','']),
			listeners:{
				itemSelected:{
					fn:this.showProperties,
					scope:this
				}
			}
		});
		
		this.rightBottom = Ext.create('Ext.Panel',{
			region:'center',
			split:true,
			layout:'fit',
			title:desLang.properties,
			collapsible:true,
			border:false
		});
		
		this.rightPanel = Ext.create('Ext.Panel',{
			region:'east',
			split:true,
			minWidth:250,
			width:250,
			collapsible:true,
			layout:'border',
			items: [this.rightTop , this.rightBottom]
		});
		
		// Center
		this.centerPanel = Ext.create('Ext.Panel',{
			region:'center',
			border:false,
			split:true,
			layout:'fit',
			html:'<iframe id="viewFrame" style="width:100%;height:100%;border:0;" src="" />'
			
		});
		
		this.items = [this.rightPanel, this.centerPanel];
	},
	
	initToolbars:function(){
		
		
		this.dockedItems = [{
		        xtype: 'toolbar',
				dock: 'left',
				defaults:{
					showType:'loaded',
	                iconCls: 'add16',
	                scope:this,
	                handler:this.addObject
				},
				items:[
				        {
				        	text:desLang.panel,
			                icon:'/i/system/designer/panel.png',
			                tooltip: desLang.add + ' ' + desLang.panel,
			                oClass:'panel'
			            },
			            {
			            	text:desLang.tabPanel,
			            	tooltip: desLang.add + ' ' + desLang.tabPanel,
			            	icon:'/i/system/designer/tab.png',
			            	oClass:'tabpanel'
			            },
			            {
			            	text:desLang.grid,
			            	icon:'/i/system/designer/grid.png',
			            	tooltip: desLang.add + ' ' + desLang.grid,
			            	oClass:'grid'
			            },
			            {
			            	text:desLang.form,
			            	icon:'/i/system/designer/form.png',
			            	tooltip: desLang.add + ' ' + desLang.form,
			            	oClass:'firm'
			            },'-',
			            {
			            	text:desLang.window,
			            	icon:'/i/system/designer/window.png',
			            	tooltip: desLang.add + ' ' + desLang.window,
			            	oClass:'window' 
			            },'-',
			            {
			            	text:desLang.store,
			            	icon:'/i/system/designer/store.png',
			            	tooltip: desLang.add + ' ' + desLang.store,
			            	oClass:'store' 
			            },'-'/*,
			            {
			            	icon:'/i/system/designer/chart.png',
			            	 tooltip: desLang.add + ' ' + desLang.chart
			            }*/
	            ]
			},{
				xtype: 'toolbar',
				dock:'top',
				items:[
				       {		
				    	   text: desLang.layout,
				    	   showType:'all',
				    	   menu: Ext.create('Ext.menu.Menu', {
						   		    style: {
								        overflow: 'visible'   
								    },
								    items: [  
									   {
										   text: desLang.newInterface,
										   icon: '/i/system/designer/new.png',
										   scope:this,
										   handler:this.createProject,
										   showType:'empty'
									   },{
								           text: desLang.load,
								           icon: '/i/system/designer/open.png',
								           scope:this,
										   handler:this.selectProject,
										   showType:'empty'
								       },{
								    	   text: desLang.save,
										   icon: '/i/system/designer/save.png',
										   handler:this.saveProject,
										   scope:this,
										   showType:'loaded'
								       },{
								    	   text: desLang.saveAs,
										   icon: '/i/system/designer/save.png',
										   showType:'loaded'
								       },{
								    	   text: desLang.close,
										   icon: '/i/system/designer/exit.png',
										   scope:this,
								           handler:this.closeProject,
								           showType:'loaded'
								       }		       
								    ]
								})
			         },{
				    	   tooltip: desLang.save,
						   icon: '/i/system/designer/save.png',
						   handler:this.saveProject,
						   scope:this,
						   showType:'loaded'
				     },'-',{
				    	   tooltip: desLang.refreshView,
						   icon: '/i/system/designer/refresh.png',
						   showType:'loaded',
						   scope:this,
						   handler:this.loadInterface
				     },'-',{
			        	 icon:'/i/system/designer/store.png',
			        	 text:desLang.dbConnections,
			        	 handler:function(){
			        		 Ext.create('designer.connections.Window',{
			        			 controllerUrl:designer.controllerUrl
			        		 }).show();
			        	 },
			        	 showType:'all'
			         },{
			        	 icon:'/i/system/designer/configure.png',
			        	 text:desLang.projectConfig,
			        	 showType:'loaded',
			        	 handler:function(){
			        		 Ext.create('designer.configWindow',{
			        			 controllerUrl:designer.controllerUrl,
			        			 listeners:{
			        				 dataSaved:{
			        					 fn:this.onChange,
			        					 scope:this
			        				 }
			        			 }
			        		 }).show();
			        	 }
			         }
			     ]
		}];
	},
	onChange:function(){
		
	},
	loadInterface:function(){
		this.rightTop.loadInfo();
		this.refreshCodeframe();
	},
	createProject:function(){
		
		Ext.create('app.FilesystemWindow',{
			title:desLang.createProject,
			controllerUrl:app.createUrl([designer.controllerUrl ,'fs','']),
			viewMode:'create',
			listeners:{
				fileCreated:{
					fn:this.loadProject,
					scope:this
				}
			}
		}).show();
    },
	selectProject:function(){
		
		  Ext.create('app.FilesystemWindow',{
			 title:desLang.selectProject,
			 viewMode:'select',
			 controllerUrl:app.createUrl([designer.controllerUrl ,'fs','']),
			 listeners:{
				 fileSelected:{
					 fn:this.loadProject,
					 scope:this
				 }
			 }
		 }).show();
	 },
	 loadProject:function(name){
		 var me = this;
			me.getEl().mask(appLang.LOADING);
			Ext.Ajax.request({
			 	url:app.createUrl([designer.controllerUrl ,'project','load']),
			 	method: 'post',
			 	params:{
			 		file:name
			 	},
			    success: function(response, request) {
			 		response =  Ext.JSON.decode(response.responseText);
			 		if(response.success){
			 			me.checkIsLoaded();
			 		}else{
			 		    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
			 		}
			 		me.getEl().unmask();
			    },
			    failure:function() {
			       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
			       	me.getEl().unmask();
			    }
			 });
	 },
	 checkIsLoaded:function(){	
		 Ext.Ajax.request({
			 	url:app.createUrl([designer.controllerUrl ,'project','checkloaded']),
			 	method: 'post',
			 	scope:this,
			    success: function(response, request) {
			 		response =  Ext.JSON.decode(response.responseText);
			 		if(response.success){
			 			this.prepareInterface(true);
			 			this.loadInterface();
			 		}
			    },
			    failure:function() {
			       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
			    }
		});
	 },
	 /**
	  * Save project
	  * @param callback - optional
	  */
	 saveProject:function(callback)
	 {
		 Ext.Ajax.request({
			 	url:app.createUrl([designer.controllerUrl ,'project','save']),
			 	method: 'post',
			    success: function(response, request) {
			 		response =  Ext.JSON.decode(response.responseText);
			 		if(response.success){
			 			designer.msg(appLang.MESSAGE , desLang.msg_projectSaved);
			 			if(callback == 'function')
			 				callback();
			 		}else{
			 		    Ext.Msg.alert(appLang.MESSAGE,response.msg);   	
			 		}
			    },
			    failure:function() {
			       	Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
			    }
			 });	 
	 },
	 /**
	  * Close project
	  */
	 closeProject:function(){
		 var me = this;
		 Ext.Msg.confirm(appLang.CONFIRMATION, appLang.MSG_SAVE_BEFORE_CLOSE, function(btn){		 
			 if(btn == 'yes'){
				 var callbackFunc = function(){
					 me.prepareInterface(false);
					 me.clearSession();
				 };
				 me.saveReport(callbackFunc);
			 }else{
				 me.clearSession();
				 me.prepareInterface();
			 }
			   
		 }, this);
	 },
	 /**
	  * Prepare buttons
	  */
	 prepareInterface:function(asLoaded){
		 /*
		  * Prepare menu items
		  */	 
		 Ext.each(this.getDockedItems('toolbar'),function(toolbar){
			 
			 Ext.each(toolbar.query('button , menuitem'), function(item , index){
				 
				 if(item.showType === 'all'){
					 return;
				 }
				 
				 if(asLoaded) {
					(item.showType == 'loaded')?item.enable():item.disable();					
				 }else{
					 (item.showType=='loaded')?item.disable():item.enable();					
				 }
			 },this);
			 
		 },this);
		 
		 //this.rightTop.clearData();
		 //this.rightBottom.removeAll();
		 //this.refreshCodeframe();
	 },
	 /**
	  * Clear session
	  */
	 clearSession:function(){
		 Ext.Ajax.request({
			 	url:app.createUrl([designer.controllerUrl ,'project','close']),
		 		method: 'post',
		        failure:function() {
		       		Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);   
		        }
		 });
	 },
	 addObject:function(btn){
		 var oClass = btn.oClass;
		 var oParent = 0;
		 var me = this;
		 
		 Ext.MessageBox.prompt(appLang.MESSAGE , desLang.enterObjectName,function(btn , text){
			 if(btn !='ok'){
				 return;
			 }
			 
			 Ext.Ajax.request({
					url:app.createUrl([designer.controllerUrl ,'project','addobject']),
					method: 'post',
					params:{
						'name':text,
						'class':oClass,
						'parent':oParent
					},
					success: function(response, request) {
						response =  Ext.JSON.decode(response.responseText);
						if(response.success){
							designer.msg(desLang.success , desLang.objectAdded);
							me.onChange();
						}else{
							Ext.Msg.alert(appLang.MESSAGE, response.msg);
						}
					},
					failure:function() {
						Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_LOST_CONNECTION);
					}
				});
		 });
	 },
	 /**
	  * Show object properties Panel
	  * @param string objectName
	  * @param string objectClass
	  * @param string objectTitle
	  */
	 showProperties:function(objectName , objectClass , objectTitle){
		 this.rightBottom.removeAll();	 
		 var panelClass = null;
		 
		 switch(objectClass){
		 	case 'Panel': panelClass = 'designer.properties.Panel';
		 		break;
		 } 
		 var me = this;
		 this.rightBottom.setTitle('<span style="color:blue">'+objectTitle+' </span> ' + desLang.properties);
		 this.activePropertyPanel = Ext.create(panelClass,{
			 controllerUrl: app.createUrl([designer.controllerUrl ,'properties','']),
			 objectName:objectName,
			 listeners:{
				 dataSaved:{
					 fn:me.refreshCodeframe,
					 scope:me
				 }
			 }
		 });
		 
		 this.rightBottom.add(this.activePropertyPanel);
	 },
	 refreshCodeframe:function(){
		 var dt = new Date();
		 var frame = Ext.get('viewFrame');
		 frame.set({
			src: app.createUrl([designer.controllerUrl ,'viewframe','index',dt.getTime()])
		 });
	}
});
